#include <iostream>
#include <cstring>

//c
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>

int main() {
    /*        server          |      client
            accept(block)     |         
                ↓           <---     connect
            read(block)       |       
                ↓           <---      write
              do sth..
    */
    //https://mp.weixin.qq.com/s/YdIdoZ_yusVWza1PU7lWaw

    int socketfd = socket(AF_INET, SOCK_STREAM, 0);
    if (socketfd == -1)
        return -1;

    sockaddr_in addrServer;
    addrServer.sin_family = AF_INET;
    addrServer.sin_port = htons(SERT_PORT);
    inet_pton(AF_INET, "0.0.0.0", &addrServer.sin_addr);

    if (bind(socketfd, (sockaddr*)(&addrServer), sizeof(sockaddr_in)) == -1)
        return -1;

    if (listen(socketfd, 4) == -1)
        return -1;

    while (true) {
        sockaddr_in client;
        socklen_t len(sizeof(sockaddr_in));
        int acceptfd = accept(socketfd, (sockaddr*)(&client), &len);

        if (acceptfd == -1)
            continue;

        char buf[MAXLINE + 1] = {0};
        if (read(acceptfd, buf, MAXLINE) != 0)
            std::cout << buf << std::endl;

        write(acceptfd, buf, MAXLINE);  //echo
        
        if (std::strcmp(buf, "out") == 0)
            break;

        close(acceptfd);
    }
    
    close(socketfd);
    return 0;
}
